package com.gzu.finalwork.user.controller;

import com.gzu.finalwork.common.utils.AjaxResult;
import com.gzu.finalwork.entity.user.Addresses;
import com.gzu.finalwork.user.service.AddressStatsService;
import com.gzu.finalwork.user.service.AddressesService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/address")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class AddressesController {
    @Autowired
    private AddressesService addressesService;

    @Autowired
    private AddressStatsService addressStatsService;
    //创建新的地址
    @PostMapping("/create")
    public Object createAddress(@RequestBody Addresses addresses, HttpSession session) {
        try{
            Long userId = (Long) session.getAttribute("userId");
            addresses.setUserId(userId);
            return AjaxResult.success(addressesService.createAddress(addresses),"创建地址成功");
        }catch(Exception e){
            return AjaxResult.error(-1,"创建地址失败");
        }
    }

    //查询用户所有寄件地址
    @GetMapping("/queryAllSend")
    public Object queryAllAddress(@RequestParam(defaultValue = "1") int pageNum,
                                  @RequestParam(defaultValue = "5") int pageSize,
                                  HttpSession session) {
        try{
            Long userId = (Long) session.getAttribute("userId");
            List<Addresses> deliveryOrdersList = addressesService.selectAllAddress(userId, pageNum, pageSize);
            Integer total = addressesService.selectCountAllAddress(userId,1); // 用于分页信息
            // 构建包含分页信息的返回结果
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("list",deliveryOrdersList);
            resultData.put("total", total);
            resultData.put("pageNum", pageNum);
            resultData.put("pageSize", pageSize);
            return AjaxResult.success(resultData,"查询地址成功");
        }catch(Exception e){
            return AjaxResult.error(-1,"查询地址失败");
        }
    }

    //查询所有收货地址
    @GetMapping("/queryAllReceive")
    public Object queryAllReceiveAddress(@RequestParam(defaultValue = "1") int pageNum,
                                         @RequestParam(defaultValue = "5") int pageSize,
                                         HttpSession session) {
        try{
            Long userId = (Long) session.getAttribute("userId");
            List<Addresses> deliveryOrdersList = addressesService.selectAllReceiveAddress(userId, pageNum, pageSize);
            Integer total = addressesService.selectCountAllAddress(userId,0); // 用于分页信息
            // 构建包含分页信息的返回结果
            Map<String, Object> resultData = new HashMap<>();
            resultData.put("list",deliveryOrdersList);
            resultData.put("total", total);
            resultData.put("pageNum", pageNum);
            resultData.put("pageSize", pageSize);
            return AjaxResult.success(resultData,"查询地址成功");
        }catch(Exception e){
            return AjaxResult.error(-1,"查询地址失败");
        }
    }

    //删除地址
    @PostMapping("/delete")
    public Object deleteAddress(Long addressId) {
        try{
            addressesService.deleteAddress(addressId);
            return AjaxResult.success("删除地址成功");
        }catch(Exception e){
            return AjaxResult.error(-1,"删除地址失败");
        }
    }

    //修改地址
    @PostMapping("/update")
    public Object updateAddress(@RequestBody Addresses addresses) {
        try{
            addressesService.updateAddress(addresses);
            return AjaxResult.success("修改地址成功");
        }catch(Exception e){
            return AjaxResult.error(-1,"修改地址失败");
        }
    }

    //设置默认地址
    @PostMapping("/setDefault")
    public Object setDefaultAddress(Long addressId, HttpSession session) {
        try{
            Long userId = (Long) session.getAttribute("userId");
            addressesService.setDefaultAddress(addressId, userId);
            return AjaxResult.success("设置默认地址成功");
        }catch(Exception e){
            return AjaxResult.error(-1,"设置默认地址失败");
        }
    }

    //得到常用地址
    @GetMapping("/frequent")
    public Object getFrequentAddresses(HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return AjaxResult.error(-1, "用户未登录");
            }

            List<Map<String, Object>> frequentAddresses = addressStatsService.getTopFrequentAddresses(userId);
            return AjaxResult.success("获取常用地址成功",frequentAddresses);
        } catch (Exception e) {
            return AjaxResult.error(-1, "获取常用地址失败: " + e.getMessage());
        }
    }

    // 清理用户地址统计数据
    @DeleteMapping("/clear")
    public Object clearAddressStats(HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return AjaxResult.error(-1, "用户未登录");
            }

            addressStatsService.clearUserAddressStats(userId);
            return AjaxResult.success("清理地址统计数据成功");
        } catch (Exception e) {
            return AjaxResult.error(-1, "清理地址统计数据失败: " + e.getMessage());
        }
    }
//    // 重新地理编码
//    @PostMapping("/reGeocode")
//    public Object reGeocodeAddress(@RequestParam Long addressId) {
//        try {
//            return addressesService.reGeocodeAddress(addressId);
//        } catch (Exception e) {
//            return AjaxResult.error(-1, "重新地理编码失败，请稍后再试");
//        }
//    }
}
